<template>
  <div class="search-container" ref="fixedBox">
    <div class="search-input" @click="showSearchPage">
      <i class="material-icons">search</i>
      <input type="text" placeholder="搜索饿了么商家、商品名称" readonly>
    </div>

    <!-- 搜索页面 -->
    <div class="search-page" v-if="isSearchVisible">
      <div class="search-header">
        <div class="search-box">
          <i class="material-icons">search</i>
          <input type="text" 
                 v-model="searchText" 
                 placeholder="搜索饿了么商家、商品名称"
                 @input="handleSearch"
                 ref="searchInput">
          <i class="material-icons clear-icon" 
             v-if="searchText" 
             @click="clearSearch">close</i>
        </div>
        <span class="cancel-btn" @click="closeSearch">取消</span>
      </div>

      <!-- 搜索历史 -->
      <div class="search-history" v-if="!searchText && searchHistory.length > 0">
        <div class="section-header">
          <h3>搜索历史</h3>
          <i class="material-icons" @click="clearHistory">delete</i>
        </div>
        <div class="history-list">
          <div class="history-item" 
               v-for="(item, index) in searchHistory" 
               :key="index"
               @click="useHistoryItem(item)">
            <i class="material-icons">history</i>
            <span>{{ item }}</span>
          </div>
        </div>
      </div>

      <!-- 热门搜索 -->
      <div class="hot-search" v-if="!searchText">
        <div class="section-header">
          <h3>热门搜索</h3>
        </div>
        <div class="hot-tags">
          <span class="hot-tag" 
                v-for="(tag, index) in hotSearches" 
                :key="index"
                @click="useHotTag(tag)">
            {{ tag }}
          </span>
        </div>
      </div>

      <!-- 搜索结果 -->
      <div class="search-results" v-if="searchText">
        <div class="result-section" v-if="businessResults.length > 0">
          <h3>商家</h3>
          <div class="business-list">
            <div class="business-item" 
                 v-for="(business, index) in businessResults" 
                 :key="index"
                 @click="selectBusiness(business)">
              <img :src="business.image" :alt="business.name">
              <div class="business-info">
                <h4>{{ business.name }}</h4>
                <div class="rating">
                  <i class="material-icons">star</i>
                  <span>{{ business.rating }}</span>
                  <span class="sales">月售{{ business.monthlySales }}单</span>
                </div>
                <div class="delivery-info">
                  <span>¥{{ business.minPrice }}起送</span>
                  <span>配送费¥{{ business.deliveryFee }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="result-section" v-if="foodResults.length > 0">
          <h3>商品</h3>
          <div class="food-list">
            <div class="food-item" 
                 v-for="(food, index) in foodResults" 
                 :key="index"
                 @click="selectFood(food)">
              <img :src="food.image" :alt="food.name">
              <div class="food-info">
                <h4>{{ food.name }}</h4>
                <p class="food-desc">{{ food.description }}</p>
                <div class="food-price">
                  <span class="price">¥{{ food.price }}</span>
                  <span class="sales">月售{{ food.monthlySales }}份</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="no-results" v-if="!businessResults.length && !foodResults.length">
          <i class="material-icons">search_off</i>
          <p>未找到相关结果</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SearchBar',
  data() {
    return {
      isSearchVisible: false,
      searchText: '',
      searchHistory: [],
      hotSearches: [
        '奶茶', '炸鸡', '麻辣烫', '汉堡', 
        '披萨', '寿司', '火锅', '烧烤'
      ],
      businessResults: [],
      foodResults: [],
      allBusinesses: [
        {
          id: 1,
          name: '万家饺子（软件园E18店）',
          image: require('@/assets/sj01.png'),
          rating: 4.9,
          monthlySales: 345,
          minPrice: 15,
          deliveryFee: 3,
          foods: [
            {
              id: 1,
              name: '三鲜水饺',
              image: require('@/assets/sp01.png'),
              price: 15,
              description: '新鲜猪肉、虾仁、韭菜',
              monthlySales: 156
            },
            {
              id: 2,
              name: '韭菜鸡蛋水饺',
              image: require('@/assets/sp02.png'),
              price: 12,
              description: '新鲜韭菜、农家土鸡蛋',
              monthlySales: 98
            }
          ]
        },
        {
          id: 2,
          name: '川湘居（软件园店）',
          image: require('@/assets/sj02.png'),
          rating: 4.8,
          monthlySales: 289,
          minPrice: 20,
          deliveryFee: 4,
          foods: [
            {
              id: 3,
              name: '麻婆豆腐',
              image: require('@/assets/sp03.png'),
              price: 18,
              description: '嫩滑豆腐、麻辣鲜香',
              monthlySales: 203
            }
          ]
        }
      ]
    }
  },
  mounted() {
    // 从本地存储加载搜索历史
    const history = localStorage.getItem('searchHistory');
    if (history) {
      this.searchHistory = JSON.parse(history);
    }
  },
  methods: {
    showSearchPage() {
      this.isSearchVisible = true;
      this.$nextTick(() => {
        this.$refs.searchInput.focus();
      });
    },
    closeSearch() {
      this.isSearchVisible = false;
      this.searchText = '';
      this.businessResults = [];
      this.foodResults = [];
    },
    clearSearch() {
      this.searchText = '';
      this.businessResults = [];
      this.foodResults = [];
    },
    handleSearch() {
      if (!this.searchText) {
        this.businessResults = [];
        this.foodResults = [];
        return;
      }

      // 搜索商家
      this.businessResults = this.allBusinesses.filter(business => 
        business.name.toLowerCase().includes(this.searchText.toLowerCase())
      );

      // 搜索商品
      this.foodResults = [];
      this.allBusinesses.forEach(business => {
        const foods = business.foods.filter(food =>
          food.name.toLowerCase().includes(this.searchText.toLowerCase())
        );
        this.foodResults.push(...foods);
      });
    },
    useHistoryItem(item) {
      this.searchText = item;
      this.handleSearch();
    },
    useHotTag(tag) {
      this.searchText = tag;
      this.handleSearch();
    },
    selectBusiness(business) {
      // 保存搜索历史
      if (this.searchText && !this.searchHistory.includes(this.searchText)) {
        this.searchHistory.unshift(this.searchText);
        if (this.searchHistory.length > 10) {
          this.searchHistory.pop();
        }
        localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory));
      }
      
      // 跳转到商家详情页
      this.$router.push({
        path: '/businessInfo',
        query: { businessId: business.id }
      });
    },
    selectFood(food) {
      // 保存搜索历史
      if (this.searchText && !this.searchHistory.includes(this.searchText)) {
        this.searchHistory.unshift(this.searchText);
        if (this.searchHistory.length > 10) {
          this.searchHistory.pop();
        }
        localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory));
      }
      
      // 跳转到商品详情页
      this.$router.push({
        path: '/foodInfo',
        query: { foodId: food.id }
      });
    },
    clearHistory() {
      this.searchHistory = [];
      localStorage.removeItem('searchHistory');
    }
  }
}
</script>

<style scoped>
.search-container {
  position: relative;
}

.search-input {
  background-color: white;
  border-radius: 20px;
  display: flex;
  align-items: center;
  padding: 8px 16px;
  cursor: pointer;
}

.search-input i {
  color: #999;
  margin-right: 8px;
}

.search-input input {
  border: none;
  outline: none;
  flex: 1;
  font-size: 14px;
  background: none;
}

.search-page {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: white;
  z-index: 1000;
  display: flex;
  flex-direction: column;
}

.search-header {
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  border-bottom: 1px solid #eee;
}

.search-box {
  flex: 1;
  background-color: #f5f5f5;
  border-radius: 20px;
  display: flex;
  align-items: center;
  padding: 8px 16px;
}

.search-box input {
  flex: 1;
  border: none;
  outline: none;
  background: none;
  font-size: 14px;
  margin: 0 8px;
}

.clear-icon {
  color: #999;
  cursor: pointer;
}

.cancel-btn {
  color: var(--md-sys-color-primary);
  font-size: 16px;
  cursor: pointer;
}

.section-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
}

.section-header h3 {
  font-size: 16px;
  color: #333;
}

.history-list {
  padding: 0 16px;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.history-item i {
  color: #999;
}

.history-item span {
  color: #333;
}

.hot-tags {
  padding: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.hot-tag {
  padding: 6px 12px;
  background-color: #f5f5f5;
  border-radius: 16px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
}

.search-results {
  flex: 1;
  overflow-y: auto;
}

.result-section {
  padding: 16px;
}

.result-section h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 12px;
}

.business-item {
  display: flex;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.business-item img {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
}

.business-info {
  flex: 1;
}

.business-info h4 {
  font-size: 16px;
  color: #333;
  margin-bottom: 4px;
}

.rating {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 4px;
}

.rating i {
  color: #ffb800;
  font-size: 16px;
}

.rating span {
  font-size: 14px;
  color: #666;
}

.sales {
  margin-left: 8px;
  color: #999;
}

.delivery-info {
  font-size: 12px;
  color: #999;
}

.food-item {
  display: flex;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.food-item img {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
}

.food-info {
  flex: 1;
}

.food-info h4 {
  font-size: 16px;
  color: #333;
  margin-bottom: 4px;
}

.food-desc {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.food-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  color: #ff4d4f;
  font-size: 16px;
  font-weight: 500;
}

.no-results {
  padding: 48px 0;
  text-align: center;
  color: #999;
}

.no-results i {
  font-size: 48px;
  margin-bottom: 16px;
}
</style> 